# -*- coding: utf-8 -*-
"""
@Time ： 2021/11/18 18:37
@Auth ： Jolg
@File ：menu.py
@IDE ：PyCharm

"""
import json

from fastapi import APIRouter,Depends, FastAPI, Header, HTTPException,File, UploadFile,Body,Response,Form
import sys
sys.path.append("..")
from conf import config
from conf import logger,db
from utils import auth_user
from typing import List,Optional
from utils.resp import *
from utils.mydb import Page
router = APIRouter()

@router.get("/menusList",summary='菜单列表')
async def MenusList(page :Page= Depends(Page),user :auth_user.Check_user= Depends(auth_user.Check_user)):
    sql1 = '''select t.*  from menus t '''
    menu = db.querypagedict(page,sql1,())
    sqlct = '''select count(1) ct from menus t '''
    ct = db.querydict(sqlct, ())
    logger.info(menu)
    data = {"menu": menu,"count":ct[0]['ct'],"currentPage":page.PAGEINDEX,"currentCount":len(menu)  }
    return success(data)

def  menu_recursive(parentid):
    sql1 = '''select t.*  from menus t  where t.parent=%s'''
    c = db.querydict(sql1,(parentid))
    # logger.info(c)
    if len(c)>0:
        for s in range(len(c)):
            if c[s]['type']=='dir':
                c[s]['children']=menu_recursive(c[s]['id'])
        return c

@router.get("/menusTree",summary='菜单树')
async def MenusTree(user :auth_user.Check_user= Depends(auth_user.Check_user)):
    menu = menu_recursive(0)
    # logger.info(menu)
    data = {"menu": menu}
    return success(data)

@router.put("/menusList",summary='添加菜单')
async def addMenu(user :auth_user.Check_user= Depends(auth_user.Check_user)):
    sql1 = '''select t.*  from menus t '''
    menu = db.querydict(sql1,())
    logger.info(menu)
    data = {"menu": menu}
    return success(data)

@router.delete("/menusList",summary='删除菜单')
async def delMenu(type:int=Body(1),menuId: List[int]=Body(...),user :auth_user.Check_user= Depends(auth_user.Check_user)):
    ids = f'''({",".join(map(str, menuId))})'''
    logger.info(ids)
    sql = f'''delete from menus t where t.id in {ids} '''
    db.duexe(sql,())
    return success()